07. Solution: Defining a Functional Interface

Solution: Defining a Functional Interface

ND079 JPND C2 L01 A05 Solution Defining A Functional Interface

BinaryOperation.java

@FunctionalInterface
public interface BinaryOperation {
  int apply(int a, int b);
}

Main.java

public final class Main {
  public static void main(String[] args) {
    BinaryOperation add = (a, b) -> a + b;
    // Or you could use:
    //
    //  BinaryOperation add = Integer::sum;
    //
    // More on method references later!

    assert 5 == add.apply(2, 3);
  }
}

Alternative Solution

If you were paying really close attention, you may have noticed you can avoid creating a custom functional interface altogether — just use java.util.function.BinaryOperator with a type parameter of Integer! Then your Main.java method would look like this:

Main.java

public final class Main {
  public static void main(String[] args) {
    BinaryOperator<Integer> add = (a, b) -> a + b;
    assert 5 == add.apply(2, 3);
  }
}

Take a moment to look at some of the other predefined functional interfaces in Java's built-in java.util.function package. It might save you some work in the future!